package com.vueblog.webapi.controller.admin;


import com.vueblog.webapi.controller.BaseController;
import com.vueblog.webapi.exception.BusinessException;
import com.vueblog.webapi.request.BasePageRequest;
import com.vueblog.webapi.request.CreateOrUpdateTypeRequest;
import com.vueblog.webapi.response.BasePageResponse;
import com.vueblog.webapi.response.BaseResponse;
import com.vueblog.webapi.service.ITypeService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author luosj
 * @since 2021-05-15
 */
@Controller
@CrossOrigin
@RequestMapping("/admin/types")
public class TypeController extends BaseController {

    @Autowired
    private ITypeService typeService;

    /**
     * 分类管理页面
     */
    @GetMapping("/index")
    public String typesIndexPage() {
        return "admin/types";
    }

    /**
     * 分页查询分类
     */
    @PostMapping("/list")
    @ResponseBody
    public BasePageResponse getTypePageList(@RequestBody @Valid BasePageRequest request, BindingResult bindingResult) {
        checkBindingResult(bindingResult);
        return typeService.getTypePageList(request);
    }

    /**
     * 分类列表（下拉框模式）
     */
    @GetMapping("/list")
    @ResponseBody
    public BaseResponse getTypeList() {
        return typeService.getTypeList();
    }

    /**
     * 创建分类
     */
    @PostMapping("/create")
    @ResponseBody
    public BaseResponse createType(@RequestBody @Valid CreateOrUpdateTypeRequest request, BindingResult bindingResult) throws IllegalAccessException {
        checkBindingResult(bindingResult);
        try {
            return typeService.createType(request);
        } catch (BusinessException e) {
            return new BaseResponse(-1, e.getMsg());
        }
    }

    /**
     * 编辑分类
     */
    @PutMapping("/update/{id}")
    @ResponseBody
    public BaseResponse updateTypeInfo(@RequestBody @Valid CreateOrUpdateTypeRequest request, BindingResult bindingResult, @PathVariable("id") String id) {
        checkBindingResult(bindingResult);
        try {
            return typeService.updateTypeInfo(request, id);
        } catch (BusinessException e) {
            return new BaseResponse(-1, e.getMsg());
        }
    }

    /**
     * 删除分类
     */
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public BaseResponse deleteTypeInfo(@PathVariable("id") String id) {
        return typeService.deleteTypeInfo(id);
    }
}
